package com.forlove.app.qselect.friend.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.forlove.app.R;
import com.forlove.app.common.base.event.BaseMessageEvent;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.manager.ContactsManager;
import com.forlove.app.manager.EventManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.async.LoadContactsAsync;
import com.forlove.app.qselect.answer.entity.AnswerEntity;
import com.forlove.app.qselect.answer.ui.AnswerSubjectActivity;
import com.forlove.app.qselect.friend.adapter.InviteContactsAdapter;
import com.forlove.app.qselect.friend.adapter.SearchInviteContactsAdapter;
import com.forlove.app.qselect.friend.entity.ContactsFriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.entity.NewsFriendsStatus;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.presenter.InviteContactsPresenter;
import com.forlove.app.qselect.friend.view.InviteContactsView;
import com.forlove.app.qselect.friend.widget.contact.SideBarView;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 邀请通讯录中未注册好友
 * 按魅力值排序
 * Created by yjl on 2017/11/17.
 */

@RuntimePermissions
public class InviteContactsActivity extends BaseActivity<InviteContactsPresenter> implements
        InviteContactsView, SideBarView.LetterSelectListener,
        LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>>,
        View.OnClickListener, TextWatcher {

    @BindView(R.id.image_back)
    ImageView image_back;

    @BindView(R.id.tool_view)
    RelativeLayout toolsView;  //toolbar view

    @BindView(R.id.image_search)
    ImageView image_search;  //搜索图标

    @BindView(R.id.view_search)
    RelativeLayout view_search; //搜索框

    @BindView(R.id.edittext_input_query)
    AppCompatEditText edittext_input_query; //输入搜索内容

    @BindView(R.id.text_cancel_query)
    AppCompatTextView text_cancel_query; //取消


    @BindView(R.id.expandale_list_friend)
    ExpandableListView friendListView;  //分组的手机联系人

    @BindView(R.id.list_search_result)
    RecyclerView list_search_result;  //获取搜索结果的页面

    @BindView(R.id.view_side_contacts)
    SideBarView view_side_contacts;

    private String from = "";
    private List<ContactsInfoEntity> contactsInfoEntities = new ArrayList<>(); //本地通讯录所有人
    private LoadContactsAsync loadContactsAsync;  //异步加载手机通讯录
    private InviteContactsAdapter inviteContactsAdapter;  //联系人分组list adapter
    private List<MineFriendEntity> canInviteFriend = new ArrayList<>();  //列表显示的好友
    private List<MineFriendEntity> registerFriend = new ArrayList<>(); //已经注册好友
    private List<MineFriendEntity> unRegisterFriend = new ArrayList<>(); //未注册好友
    private List<MineFriendEntity> searchFriend = new ArrayList<>();//搜索的好友
    private SearchInviteContactsAdapter searchInviteContactsAdapter;//搜索好友的adapter
    private String quryStr; //输入搜索的str

    private LoadContactsAsync createContacts() {
        if (loadContactsAsync == null) {
            loadContactsAsync = new LoadContactsAsync(this);
        }
        return loadContactsAsync;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_firend_invite_phone;
    }


    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new InviteContactsPresenter(this);
        }

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            from = bundle.getString("from");
        }
        image_back.setOnClickListener(this);
        image_search.setOnClickListener(this);
        text_cancel_query.setOnClickListener(this);
        edittext_input_query.addTextChangedListener(this);
        initExpandableGroupAdapter();
        initRecyclerViewAdapter();
        presenter.loadContactFriend();
        contactsInfoEntities.clear();
        contactsInfoEntities.addAll(ContactsManager.getContectInfo(this));
        //请求通讯录权限，如果成功则加载最新的通讯录
        InviteContactsActivityPermissionsDispatcher.needContactsWithPermissionCheck(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        if (inviteContactsAdapter != null) {
            inviteContactsAdapter.clearData();
        }
        if (searchInviteContactsAdapter != null) {
            searchInviteContactsAdapter.clearData();
        }
    }

    /**
     * 本地通讯录列表的展示
     */
    private void initExpandableGroupAdapter() {
        inviteContactsAdapter = new InviteContactsAdapter(this, presenter, canInviteFriend);
        friendListView.setAdapter(inviteContactsAdapter);
        friendListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        friendListView.setGroupIndicator(null);
        for (int i = 0; i < inviteContactsAdapter.getGroupCount(); i++) {
            friendListView.expandGroup(i);
        }
        view_side_contacts.setOnLetterSelectListen(this);
        if (!TextUtils.isEmpty(from)) {
            inviteContactsAdapter.setFromViewName(from);
        }
    }

    private void initRecyclerViewAdapter() {
        searchInviteContactsAdapter = new SearchInviteContactsAdapter(this,
                R.layout.item_friends_contacts, searchFriend, presenter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        list_search_result.setLayoutManager(linearLayoutManager);
        list_search_result.setAdapter(searchInviteContactsAdapter);
        searchInviteContactsAdapter.hideFooterView();
        searchInviteContactsAdapter.hideEmptyView();
        if (!TextUtils.isEmpty(from)) {
            searchInviteContactsAdapter.setFromViewName(from);
        }
        searchInviteContactsAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position < searchFriend.size()) {
                    MineFriendEntity friendEntity = searchFriend.get(position);
                    //添加好友，好友申请页面
                    if (friendEntity.status == NewsFriendsStatus.UNCONFIRM.getCode()
                            || friendEntity.status == NewsFriendsStatus.UNADDED.getCode()
                            || friendEntity.status == NewsFriendsStatus.WAITING.getCode()) {
                        SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                        searchFriendEntity.friendEntity = friendEntity;
                        searchFriendEntity.isFriend = false;
                        searchFriendEntity.note_times = friendEntity.charm;
                        Intent intent = new Intent(InviteContactsActivity.this,
                                SearchUserInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("friendinfo", searchFriendEntity);
                        bundle.putString("mobile", friendEntity.getAvaliableMobile());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else if (friendEntity.status == NewsFriendsStatus.CONFIRMED.getCode()) {
                        Intent intent = new Intent(InviteContactsActivity.this,
                                MineInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("mobile", friendEntity.mobile);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_search:
                if (toolsView.isShown()) {
                    toolsView.setVisibility(View.GONE);
                    view_search.setVisibility(View.VISIBLE);
                    SystemUtils.openInputMethod(this, image_search);
                }
                break;

            case R.id.text_cancel_query:
                view_search.setVisibility(View.GONE);
                edittext_input_query.setText("");
                toolsView.setVisibility(View.VISIBLE);
                SystemUtils.hideKeyBoard(this, text_cancel_query);
                if (!friendListView.isShown()) {
                    friendListView.setVisibility(View.VISIBLE);
                    list_search_result.setVisibility(View.GONE);
                    view_side_contacts.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.image_back:
                onBackPressed();
                break;
        }
    }


    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
        if (data != null) {
            contactsInfoEntities.clear();
            contactsInfoEntities.addAll(data);
            showDataview();
        }
    }

    private void showDataview() {
        canInviteFriend.clear();
        canInviteFriend.addAll(FriendManager.getUnregContactsFriends(contactsInfoEntities, unRegisterFriend, registerFriend));
        inviteContactsAdapter.updateFriendList(canInviteFriend);
        inviteContactsAdapter.notifyDataSetChanged();
        for (int i = 0; i < inviteContactsAdapter.getGroupCount(); i++) {
            friendListView.expandGroup(i);
        }
    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {

    }

    @Override
    public void onLetterSelected(String letter) {
        setListViewPosition(letter);
    }

    @Override
    public void onLetterChanged(String letter) {
        setListViewPosition(letter);
    }

    @Override
    public void onLetterReleased(String letter) {
        setListViewPosition(letter);
    }

    private void setListViewPosition(String letter) {
        int firstLetterPosition = inviteContactsAdapter.getFirstFriendPosition(letter);
        if (firstLetterPosition != -1) {
            friendListView.setSelection(firstLetterPosition);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        quryStr = editable.toString().replaceAll(" ", "");
        if (TextUtils.isEmpty(quryStr)) {
            friendListView.setVisibility(View.VISIBLE);
            list_search_result.setVisibility(View.GONE);
            view_side_contacts.setVisibility(View.VISIBLE);
        } else {
            searchFriend.clear();
            searchFriend.addAll(getLocalSearchFriend(quryStr));
            searchInviteContactsAdapter.setQueryString(quryStr);
            searchInviteContactsAdapter.updateDatas(searchFriend);
            friendListView.setVisibility(View.GONE);
            view_side_contacts.setVisibility(View.GONE);
            list_search_result.setVisibility(View.VISIBLE);
        }
    }

    private List<MineFriendEntity> getLocalSearchFriend(String queryStr) {
        List<MineFriendEntity> local = new ArrayList<>();
        for (MineFriendEntity friendEntity : canInviteFriend) {
            if (friendEntity.contactsName.contains(queryStr)
                    || friendEntity.contactsNumber.contains(queryStr)
                    || (!TextUtils.isEmpty(friendEntity.realname)
                    && friendEntity.realname.contains(queryStr))) {
                local.add(friendEntity);
            }
        }
        return local;
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void needContacts() {
        getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        InviteContactsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void updateFriendListView(ContactsFriendEntity contactsFriendEntity) {
        registerFriend.clear();
        registerFriend.addAll(contactsFriendEntity.concats);
        unRegisterFriend.clear();
        unRegisterFriend.addAll(contactsFriendEntity.concats_unreg);
        showDataview();
    }

    @Override
    public void onEventMainThread(BaseMessageEvent event) {
        super.onEventMainThread(event);
        if (event.eventId == EventManager.EVENT_INVITE_CONTACTS) {
            this.finish();
        }
    }

    @Override
    public void showResetAnswerView(AnswerEntity answerEntity) {
        Intent intent = new Intent(this, AnswerSubjectActivity.class);
        Bundle bundle = new Bundle();
        if (answerEntity != null) {
            bundle.putSerializable("answer", answerEntity.serializeToString());
        }
        intent.putExtras(bundle);
        startActivity(intent);
        this.finish();
    }
}
